<?php
/**
 * Created by PhpStorm.
 * User: root
 * Date: 2016/10/8
 * Time: 21:32
 */

namespace Home\Controller;


use Think\Controller;
use Think\Exception;
use Home\Logic\PayLogic;

vendor('WxPay');
vendor('Wxpay.WxPay_Notify');
vendor('Wxpay.WxPay_Api');
vendor('Wxpay.log');
//vendor('Wxpay.WxPay_Data');
class PayNotifyCallBack extends \WxPayNotify
{
    //查询订单
    public function Queryorder($transaction_id)
    {
        $input = new \WxPayOrderQuery();
        $input->SetTransaction_id($transaction_id);
        $result = \WxPayApi::orderQuery($input);
        if(array_key_exists("return_code", $result)
            && array_key_exists("result_code", $result)
            && $result["return_code"] == "SUCCESS"
            && $result["result_code"] == "SUCCESS")
        {
            return true;
        }
        return false;
    }

    //重写回调处理函数
    public function NotifyProcess($data, &$msg)
    {
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $notfiyOutput = array();
        if(!array_key_exists("transaction_id", $data)){
            $msg = "输入参数不正确";
            $log->DEBUG($msg);
            return false;
        }
        //查询订单，判断订单真实性
        if(!$this->Queryorder($data["transaction_id"])){
            $msg = "订单查询失败";
            $log->DEBUG($msg);
            return false;
        }
        $money = $data['total_fee'];
        $logic = new PayLogic();
        $success = $logic->weChatPaySuccess($data['out_trade_no'],$money);
        $log->DEBUG('success:'.$success);
        $log->DEBUG('out_trade_no:'.$data['out_trade_no']);
        if($success == 1){
            return true;
        }else{
            return false;
        }
        return true;
    }
}
class PayBackController extends Controller
{
    public function prepareRecharge(){
        try{
        $money = I('money');
        $user = session('user');
        $openid = session('openid');
        $lowMoney = M('config')->where(array('name'=> 'agent_recharge'))->getField('value');
            if(!isset($openid)){
//                flock( LOCK_UN);
                $wechat = new WeChatController();
                $wechat->login();
                return;
            }
        if (!isset($user) || $user['id'] == 1) {
            //跳转到首页
            $this->redirect('/Home/Index/index');
        }
        $user = D('Users')->find($user['user_id']);
        if(!is_numeric($money)){
            $this->assign('success',false);
            $this->assign('msg','请勿非法提交');
            $this->display('weChatPay');
            return;
        }
        //判断传过来的金额是否小于成为代理商的最小金额
            //不需要判断因为充值可以充值任意金额该判断移到充值成功回调函数
     /*   if($money < $lowMoney){
                $this->assign('success',false);
                $this->assign('msg','金额不足');
                $this->display('weChatPay');
                return;
            }*/
        //生成订单
            D('RechargeOrder')->startTrans();
            $data['user_id'] = $user['user_id'];
            $data['money'] = $money;
            $data['state'] = 0;
            $data['order_sn'] = build_order_no();
            $data['create_time'] = time();

        $order_id = D('RechargeOrder')->add($data);
        $order = D('RechargeOrder')->find($order_id);
        if($order_id){
            $this->makeWeChatPay($openid, '集品商城充值','充值', $order, $money);
            $this->assign('success',true);
            $this->assign('recharge','1');
            D('RechargeOrder')->commit();
            $this->display('weChatPay');
            return;
        }else{
            $this->assign('success',false);
            $this->display('weChatPay');
            D('RechargeOrder')->rollback();
            return;
        }
        }catch (\WxPayException $e){
            $this->assign('success', false);
            $this->assign('msg', '请求超时');
            D('RechargeOrder')->rollback();
            $this->display("weChatPay");
            return;
        }
    }
    //微信支付
    public function weChatPay($useMoney=0){
        $file = 'pay.txt';
        $fp = fopen($file, 'a+');
        flock($fp, LOCK_EX);
        try {
            $user = session('user');
            $user = M('users')->where(array('user_id'=> $user['user_id']))->find();
            $openid = $user['openid'];
      //      $this->jsonReturn($fp,array('success'=>false,'message'=>'你已经执行到这了'));
      //      如果没有openid就调用WeChat 下的invite方法获取网页授权
            if(!isset($openid)){
                flock($fp, LOCK_UN);
                fclose($fp);
                $wechat = new WeChatController();
                $wechat->login();
                return;
            }
            if (!isset($user) || $user['user_id'] == 1) {
                //跳转到首页
                flock($fp, LOCK_UN);
                fclose($fp);
                $this->redirect('/Home/Index/index');
            }
            $order_id = I('order_id');
            $order = M('Order')->where(array('order_id'=> $order_id, 'is_delete'=> 0))->find();
            if(!$order)
                $this->returnMessage($fp, '订单不存在或已删除');

            //判断用户是否使用余额支付一部分
            if($useMoney){
                //判断余额是否充足
                if($user['user_money']+ $user['rebate_money'] >= $order['order_amount']){
                    var_dump('11123');
                    $this->returnMessage($fp, '余额足够购买');
                    return ;
                }
                $order_amount = number_format($order['order_amount']-$user['user_money'] -  $user['rebate_money'],2);
                $order['user_money'] = $user['user_money'] + $user['rebate_money'];
                M('Order')->save($order);
//                var_dump($order_amount);
            }
            else {
                $order_amount = $order['order_amount'];
                $order['user_money'] = 0;
                M('Order')->save($order);
            }

            $this->makeWeChatPay($openid, '集品商城' , '集品商城' , $order, $order_amount);
            $this->assign('success', 'true');
//            $this->assign('kaituan', $kaituan);
            $this->assign('recharge', '0');
            flock($fp, LOCK_UN);
            fclose($fp);
            $this->display();
        }catch (\WxPayException $e){
            $this->returnMessage($fp,'订单创建失败');
        }
    }

    public function weChatPayRtn(){
        //初始化日志
        if (!is_dir('./logs/')) {
            mkdir('./logs/', 0755, true);
        }
        echo 'weChatPayRtn';
        $logHandler= new \CLogFileHandler("./logs/".date('Y-m-d').'.log');
        $log = \Log::Init($logHandler, 15);
        $notify = new PayNotifyCallBack();
        $log->DEBUG('begin notify');
        $notify->Handle(true);
    }

    /**
     * 构造微信支付页面
     * @param $user
     * @param $description
     * @param $title
     * @param $order
     * @param $money
     * @throws \WxPayException
     */
    private function makeWeChatPay($user,$description, $title, $order, $money)
    {
        vendor('WxPay');
        vendor('Wxpay.WxPay_JsApiPay');
        vendor('Wxpay.WxPay_Api.php');
        $tools = new \JsApiPay();
        $openId = $user;
        //②、统一下单
        $input = new \WxPayUnifiedOrder();
        $description =mb_substr($description,0,20,'utf-8');
        $title =mb_substr($title,0,10,'utf-8');
        $input->SetBody($description);
        $input->SetAttach("test");
        $input->SetOut_trade_no($order['order_sn']);
        $input->SetTotal_fee($money*100);
//        $input->SetTotal_fee(1);
//        $input->SetTotal_fee($money);
        $input->SetTime_start(date("YmdHis"));
        $input->SetTime_expire(date("YmdHis", time() + 600));
        $input->SetGoods_tag($title);
        $root_path = C('ROOT_PATH');
        $input->SetNotify_url($root_path . "Home/PayBack/weChatPayRtn");
        $input->SetTrade_type("JSAPI");
        $input->SetOpenid($openId);
        $order = \WxPayApi::unifiedOrder($input);
        $jsApiParameters = $tools->GetJsApiParameters($order);

        //获取共享收货地址js函数参数
        $editAddress = $tools->GetEditAddressParameters();
        $this->assign('jsApiParameters', $jsApiParameters);
        $this->assign('editAddress', $editAddress);
        $this->assign('money', $money);
    }

    /**
     * 控制器解除返回数据文件锁
     * @param $fp
     * @param $array
     */
    protected function jsonReturn($fp, $array)
    {
        flock($fp, LOCK_UN);
        fclose($fp);
        $this->ajaxReturn($array);
    }




    public function readyWechatPay()
    {
        $pay_type = I('pay_type');
        $orderInfo = I('orderinfo');

        session('pay_type', $pay_type);
        session('orderinfo', $orderInfo);
        $this->ajaxReturn(array('success' => true, 'state'=>4));
    }

    private function returnMessage($fp,$message){
        $this->assign('success', 'false');
        $this->assign('msg', $message);
        flock($fp, LOCK_UN);
        fclose($fp);
        $this->display();
    }



//    public function readyRecharge(){
//        session('rechargeMoney', I('money'));
//        $this->ajaxReturn(array('success' => true, 'ready'=>'1'));
//    }

}
